package com.wang.mall.listener;

import com.rabbitmq.client.Channel;
import com.wang.mall.bean.OmsOrder;
import com.wang.mall.service.ProductService;
import com.wang.mall.to.rabbitmq.StockLockedTo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@RabbitListener(queues = "wang-stock-release-queue")
@Service
public class ReleaseLockStockListener {

    @Autowired
    ProductService productService;

    @RabbitHandler
    public void releaseLockStock(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        // 解锁库存工作单
        try {
            // 当前消息是否是第二次,及以后(重新派发过来的)
//            Boolean redelivered = message.getMessageProperties().getRedelivered();
            productService.releaseLockStock(stockLockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handlerOrderCloseRelease(OmsOrder omsOrder,Message message, Channel channel) throws IOException {
        System.out.println("订单关闭, 解锁订单的库存");
        // 解锁库存工作单
        try {
            productService.releaseLockStock(omsOrder);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
